/**
 * 临时通行证管理js
 * Created by TomSean on 2017/4/18.
 */

var TempPassManager = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
TempPassManager.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find('.search-panel'));
        var functionArray = [
            {fName : 'search_btn', fs : this.findData},
            {fName : 'reset_btn', fs : this.resetInfo}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList({div:_this.$parent.find('#trafficPermitStatus'), parentModelKey:BASIS.TRAFFIC_PERMIT_STATUS.ROOT}, _this);
        this.initTable();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    initTable : function () {
        var _this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="temp_pass_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="uniqueIdentifier" value="${uniqueIdentifier}">'
            },
            {
                width : 250,
                title : '通行证编号',
                field : 'uniqueIdentifier'
            },
            {
                width : 250,
                title : '逻辑编号',
                field : 'rationUniqueIdentifier'
            },
            {
                width : 250,
                title : '生效时间(起~止)',
                template : '#:data.beginTime# ~ #:data.endTime#'
            },
            {
                width : 250,
                title : '创建时间',
                field : 'createTime'
            },
            {
                width: 90,
                title : '通行证类型',
                field : 'crTrafficPermitType.trafficPermitName'
            },
            {
                width: 90,
                title : '状态',
                template:"#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_PERMIT_STATUS.ROOT, trafficPermitStatus)#"
            }
        ];
        this.sysUtils.createGird(this.$parent.find("#temp_pass_data_list"),
            {
                selectable : 'single',
                autoSync : true,
                columnMenu : true,
                pageable : {input : true, numeric : false},
                columns : columns,
                change : function(e) {
                    var selected = $.map(this.select(), function(itm) {
                        return $(itm).find("input[type=checkbox]").val();
                    });
                    _this.selectRowId = selected[0];
                },
                dataBound : function() {
                    var $list = _this.$parent.find("#temp_pass_data_list");
                    $list.find("tr").unbind("dblclick");
                    $list.find("tr").dblclick(function(e){
                        var grid = $list.data("kendoGrid");
                        var dataItem = grid.dataItem(grid.select());
                        //打开查看窗口
                        _this.isEdit = false;
                        // _this.openReadWindow(dataItem["ownerCode"]);
                    });
                }
            });
    },
    findData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var grid = _this.$parent.find('#temp_pass_data_list').data('kendoGrid');
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        var dataT = {jsonData : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({url : baseApiPath + 'temp_pass/list', data : dataT, dataType : 'odata'});
        grid.setDataSource(dataSource);
    },
    openNewWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.newDiv = _this.sysUtils.openWindow(_this.newDiv, {
            title : '批量开卡',
            height : "600px",
            width : "680px",
            resizable : false,
            content : "views/parkLotCenter/parkingLotInfo/tempPassEdit.html",
            close : function() {
                clearInterval(tempPassEdit.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
                _this.findData();
            }
        }, true);
    },
    openCancelWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.cancelDiv = _this.sysUtils.openWindow(_this.cancelDiv, {
            title : '批量注销',
            height : "485px",
            width : "680px",
            resizable : false,
            content : "views/parkLotCenter/parkingLotInfo/tempPassCancel.html",
            close : function() {
                clearInterval(tempPassCancel.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
                _this.findData();
            }
        }, true);
    },
    openSearchCard : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.cancelDiv = _this.sysUtils.openWindow(_this.cancelDiv, {
            title : '检测卡',
            height : "485px",
            width : "680px",
            resizable : false,
            content : "views/parkLotCenter/parkingLotInfo/tempPassSearch.html",
            close : function() {
                clearInterval(tempPassSearch.timerRead);
                websocketFunManager.removeWebSocket(_this.$parent.parents("li").attr("data-code"));
                this.destroy();
                _this.findData();
            }
        }, true);
    }
}
var devInfos = [];
var TempPassEdit = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, tempPass.$parent);
    this.init();
    return this;
}
TempPassEdit.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'check_device', fs : this.checkDevice},
            {fName : 'cancel', fs : function() { $('#' + tempPass.newDiv).data('kendoWindow').close(); clearInterval(_this.timerRead); tempPass.findData(); }}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                select:function(e){
                    _this.checkdevice_status = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);
        this.$parent.find('#beginTime').kendoDatePicker({
            change : function() {
                _this.load$beginTime = this.value().pattern("yyyy-MM-dd");
            }
        });
        var curDate = new Date();
        var endDate = new Date(curDate.getFullYear()+1, curDate.getMonth(), curDate.getDate());
        this.sysUtils.mvvmModel.set("beginTime", curDate);
        this.$parent.find('#endTime').kendoDatePicker({
            change : function() {
                _this.load$endTime = this.value().pattern("yyyy-MM-dd");
            }
        });
        this.sysUtils.mvvmModel.set("endTime", endDate);
        Utils.createDataDictDropDownList({div:this.$parent.find('#trafficStatus'), parentModelKey:BASIS.TRAFFIC_PERMIT_STATUS.ROOT, select:Utils.getModelValueByModelKey(BASIS.TRAFFIC_PERMIT_STATUS.ENABLE)}, this);
        JsonpAjax(baseApiPath + 'traffic_permit_type/list/temp', undefined, 'json', function(res) {
            var $type = _this.$parent.find('#trafficPermitType').kendoDropDownList({
                dataTextField : "trafficPermitName",
                dataValueField : "id",
                dataSource : res
            }).data('kendoDropDownList');
            $type.select(0);
        }, true);
        var console = function () { this.div = _this.$parent.find('#console'); }
        console.prototype.print = function(str) { this.div.prepend(str) }
        _this.console = new console();
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkdevice_status = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            _this.$parent.find('#device_status').html('请先选择一个读卡器');
            _this.$parent.find('#device_status').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext" : result.deviceName + "设备已连接", "lock":0, "deviceCacheInfo":result};
        _this.devInfo = undefined;
        var jnaStr = JSON.stringify(jna);
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
        clearInterval(tempPassEdit.timerRead);
    },
    openSuccess : function(e) {
        console.log('与后台建立通信正常！');
    },
    onClose : function(e) {
        notification({title : "读卡设备异常", message : "连接断开，请检查设备、网络是否正常，再重新尝试读卡"}, 'info');
        clearInterval(tempPassEdit.timerRead);
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(tempPassEdit.readCardSerializeNumber) && tempPassEdit.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                var phyid = result.phyid;//物理卡号
                var phytyp = result.phytyp; //物理卡类型
                var cardsno = result.cardsno;//逻辑卡号
                // 读卡成功时
                if (result.opstatus == 1) {
                    if (!isEmpty(tempPassEdit.phyid) && tempPassEdit.phyid != phyid) {
                        if (tempPassEdit.noticeMessage == '当前卡与读卡信息不同，请换会读卡时的磁卡再操作') {
                            return;
                        }
                        tempPassEdit.noticeMessage = '当前卡与读卡信息不同，请换会读卡时的磁卡再操作';
                        notification({title : '操作失败', message : '当前卡与读卡信息不同，请换会读卡时的磁卡再操作'}, 'info');
                        return;
                    }
                    if (cardsno != '0') {
                        if (tempPassEdit.noticeMessage == '此卡已发行，请注销后再操作') {
                            tempPassEdit.console.print('['+ new Date().pattern("MM/dd HH:mm:ss") +']  <span style="color:#a36d03">此卡已发行，请注销后再操作</span><br>')
                            return;
                        }
                        tempPassEdit.noticeMessage = '此卡已发行，请注销后再操作';
                        notification({title : '操作失败', message : '此卡已发行，请注销后再操作'}, 'info');
                        tempPassEdit.console.print('['+ new Date().pattern("MM/dd HH:mm:ss") +']  <span style="color:#a36d03">此卡已发行，请注销后再操作</span><br>')
                        return;
                    }
                    clearInterval(tempPassEdit.timerRead);
                    tempPassEdit.phyid = phyid;
                    tempPassEdit.phytyp = phytyp;
                    $status.css({"color":"green"});
                    $status.html(phyid);
                    tempPassEdit.readCardStatus = 1;
                    tempPassEdit.$parent.find('#phyid').val(phyid);
                    var devInfo = tempPassEdit.devInfo;
                    tempPassEdit.createTempPass(devInfo, phyid, phytyp);
                } else {
                    tempPassEdit.phyid = undefined;
                    $status.css({"color":"red"});
                    $('#readCardStatus').html('读取卡失败');
                }
            } else if (!isEmpty(tempPassEdit.checkDeviceSerializeNumber) && tempPassEdit.checkDeviceSerializeNumber == data.serialNumber) {
                // 检测设备成功时
                tempPassEdit.checkdevice_status = 1;
                tempPassEdit.checkDeviceSerializeNumber = undefined;
                var $device = tempPassEdit.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem($device.select());
                tempPassEdit.devInfo = result;
                tempPassEdit.$parent.find('#device_status').html(result.deviceName + ' (' + result.deviceCode + ')');
                tempPassEdit.$parent.find('#device_status').css({'color':'green'});
                tempPassEdit.timerRead = setInterval(function() {
                    tempPassEdit.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备连接，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(tempPassEdit.timerRead);
            return;
        }
    },
    readCard : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkdevice_status != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info');
            clearInterval(tempPassEdit.timerRead);
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        tempPassEdit.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    createTempPass : function (devInfo, phyid, phytyp) {
        var _this = this;
        clearInterval(_this.timerRead);
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        params['trafficPermitType'] = _this.$parent.find('#trafficPermitType').val();
        var dataT = {'devInfo':devInfo, 'phyid':phyid, 'phytyp':phytyp, 'params':params};
        JsonpAjax(baseApiPath + 'temp_pass/create', JSON.stringify(dataT), 'json', function(res) {
            _this.successPhyid = res.value;
            _this.timerRead = setInterval(function() {
                _this.readCard();
            }, 1000);
            _this.console.print('[' + new Date().pattern("MM/dd HH:mm:ss") + ']  <span style="color: darkgreen">'+res.msg+'</span><br>');
        }, true);
    }
}

var TempPassCancel = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, tempPass.$parent);
    this.init();
    return this;
}
TempPassCancel.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'check_device', fs : this.checkDevice},
            {fName : 'cancel', fs : function() { $('#' + tempPass.cancelDiv).data('kendoWindow').close(); clearInterval(_this.timerRead); tempPass.findData(); }}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                select:function(e){
                    _this.checkdevice_status = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);

        var console = function () { this.div = _this.$parent.find('#console'); }
        console.prototype.print = function(str) { this.div.prepend(str) }
        _this.console = new console();
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkdevice_status = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            _this.$parent.find('#device_status').html('请先选择一个读卡器');
            _this.$parent.find('#device_status').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext" : result.deviceName + "设备已连接", "lock":0, "deviceCacheInfo":result};
        _this.devInfo = undefined;
        var jnaStr = JSON.stringify(jna);
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
        clearInterval(tempPassCancel.timerRead);
    },
    openSuccess : function(e) {
        console.log('与后台建立通信正常！');
    },
    onClose : function(e) {
        notification({title : "读卡设备异常", message : "连接断开，请检查设备、网络是否正常，再重新尝试读卡"}, 'info');
        clearInterval(tempPassCancel.timerRead);
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(tempPassCancel.readCardSerializeNumber) && tempPassCancel.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                var phyid = result.phyid;//物理卡号
                var phytyp = result.phytyp; //物理卡类型
                var cardsno = result.cardsno;//逻辑卡号
                // 读卡成功时
                if (result.opstatus == 1) {
                    if (!isEmpty(tempPassCancel.phyid) && tempPassCancel.phyid != phyid) {
                        if (tempPassCancel.noticeMessage == '当前卡与读卡信息不同，请换会读卡时的磁卡再操作') {
                            return;
                        }
                        tempPassCancel.noticeMessage = '当前卡与读卡信息不同，请换会读卡时的磁卡再操作';
                        notification({title : '操作失败', message : '当前卡与读卡信息不同，请换会读卡时的磁卡再操作'}, 'info');
                        return;
                    }
                    if (cardsno == '0') {
                        if (tempPassCancel.noticeMessage == '此卡未发行') {
                            tempPassCancel.console.print('['+ new Date().pattern("MM/dd HH:mm:ss") +']  <span style="color:#a36d03">此卡未发行</span><br>')
                            return;
                        }
                        tempPassCancel.noticeMessage = '此卡未发行';
                        notification({title : '操作失败', message : '此卡未发行'}, 'info');
                        tempPassCancel.console.print('['+ new Date().pattern("MM/dd HH:mm:ss") +']  <span style="color:#a36d03">此卡未发行</span><br>')
                        return;
                    }
                    clearInterval(tempPassCancel.timerRead);
                    tempPassCancel.phyid = phyid;
                    tempPassCancel.phytyp = phytyp;
                    $status.css({"color":"green"});
                    $status.html(phyid);
                    tempPassCancel.readCardStatus = 1;
                    tempPassCancel.$parent.find('#phyid').val(phyid);
                    var devInfo = tempPassCancel.devInfo;
                    tempPassCancel.cancelTempPass(devInfo, phyid, phytyp, cardsno);
                } else {
                    tempPassCancel.phyid = undefined;
                    $status.css({"color":"red"});
                    $('#readCardStatus').html('读取卡失败');
                }
            } else if (!isEmpty(tempPassCancel.checkDeviceSerializeNumber) && tempPassCancel.checkDeviceSerializeNumber == data.serialNumber) {
                // 检测设备成功时
                tempPassCancel.checkdevice_status = 1;
                tempPassCancel.checkDeviceSerializeNumber = undefined;
                var $device = tempPassCancel.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem($device.select());
                tempPassCancel.devInfo = result;
                tempPassCancel.$parent.find('#device_status').html(result.deviceName + ' (' + result.deviceCode + ')');
                tempPassCancel.$parent.find('#device_status').css({'color':'green'});
                tempPassCancel.timerRead = setInterval(function() {
                    tempPassCancel.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备连接，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(tempPassCancel.timerRead);
            return;
        }
    },
    readCard : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkdevice_status != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info');
            clearInterval(tempPassCancel.timerRead);
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        tempPassCancel.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    cancelTempPass : function (devInfo, phyid, phytyp, cardno) {
        var _this = this;
        clearInterval(_this.timerRead);
        var logicNo = cardno;
        var dataT = {'devInfo':devInfo, 'phyid':phyid, 'phytyp':phytyp, 'logicNo':logicNo};
        JsonpAjax(baseApiPath + 'temp_pass/cancel', JSON.stringify(dataT), 'json', function(res) {
            _this.successPhyid = res.value;
            _this.timerRead = setInterval(function() {
                _this.readCard();
            }, 1000);
            _this.console.print('[' + new Date().pattern("MM/dd HH:mm:ss") + ']  <span style="color: darkgreen">'+res.msg+'</span><br>');
        }, true);
    }
}

var TempPassSearch = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.ws = new webSocket(this.handlerMessage, this.openSuccess, this.onClose, tempPass.$parent);
    this.init();
    return this;
}
TempPassSearch.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'check_device', fs : this.checkDevice},
            {fName : 'cancel', fs : function() { $('#' + tempPass.cancelDiv).data('kendoWindow').close(); clearInterval(_this.timerRead); tempPass.findData(); }}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        /*  获取外接设备信息 */
        JsonpAjax(baseApiPath + "externalDevice/device_info/ic", undefined, 'json', function(res) {
            var list = res;
            if (devInfos.length > 0) {
                devInfos = new Array();
            }
            for (var i = 0; i < list.length; i++) {
                devInfos.push(list[i]);
            }
            var devices = _this.$parent.find('#device').kendoDropDownList({
                dataTextField : "deviceName",
                dataValueField : "deviceCode",
                dataSource : devInfos,
                select:function(e){
                    _this.checkdevice_status = 0;
                }
            }).data('kendoDropDownList');
            devices.select(0);
        }, true);

        var console = function () { this.div = _this.$parent.find('#console'); }
        console.prototype.print = function(str) { this.div.prepend(str) }
        _this.console = new console();
    },
    checkDevice : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        clearInterval(_this.timerRead);
        _this.checkdevice_status = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        if (isEmpty(result) || isEmpty(result.deviceCode)) {
            _this.$parent.find('#device_status').html('请先选择一个读卡器');
            _this.$parent.find('#device_status').css({'color':'red'});
            return;
        }
        var jna = {"volume":1, "voicetext" : result.deviceName + "设备已连接", "lock":0, "deviceCacheInfo":result};
        _this.devInfo = undefined;
        var jnaStr = JSON.stringify(jna);
        _this.checkDeviceSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"VC").serialNumber;
        clearInterval(tempPassSearch.timerRead);
    },
    openSuccess : function(e) {
        console.log('与后台建立通信正常！');
    },
    onClose : function(e) {
        notification({title : "读卡设备异常", message : "连接断开，请检查设备、网络是否正常，再重新尝试读卡"}, 'info');
        clearInterval(tempPassSearch.timerRead);
    },
    handlerMessage : function(e) {
        var data = JSON.parse(e.data);
        var $status = $('#readCardStatus');
        if (data.msgType == "REPLY" && data.replyType == "success") {
            if (!isEmpty(tempPassSearch.readCardSerializeNumber) && tempPassSearch.readCardSerializeNumber==data.serialNumber) {
                var result = JSON.parse(data.replayMsg);
                var phyid = result.phyid;//物理卡号
                var phytyp = result.phytyp; //物理卡类型
                var cardsno = result.cardsno;//逻辑卡号
                // 读卡成功时
                if (result.opstatus == 1) {
                    if (tempPassSearch.successPhyid == phyid) {
                        return;
                    }
                    if (cardsno == '0') {
                        tempPassSearch.successPhyid = phyid;
                        if (tempPassSearch.noticeMessage == '此卡未发行') {
                            tempPassSearch.console.print('['+ new Date().pattern("MM/dd HH:mm:ss") +']  <span style="color:#a36d03">此卡未发行</span><br><br><br>')
                            return;
                        }
                        tempPassSearch.noticeMessage = '此卡未发行';
                        notification({title : '操作失败', message : '此卡未发行'}, 'info');
                        tempPassSearch.console.print('['+ new Date().pattern("MM/dd HH:mm:ss") +']  <span style="color:#a36d03">此卡未发行</span><br><br><br>')
                        return;
                    }
                    clearInterval(tempPassSearch.timerRead);
                    tempPassSearch.phyid = phyid;
                    tempPassSearch.phytyp = phytyp;
                    $status.css({"color":"green"});
                    $status.html(phyid);
                    tempPassSearch.readCardStatus = 1;
                    tempPassSearch.$parent.find('#phyid').val(phyid);
                    var devInfo = tempPassSearch.devInfo;
                    tempPassSearch.searchTempPass(devInfo, phyid, phytyp, cardsno);
                } else {
                    tempPassSearch.phyid = undefined;
                    $status.css({"color":"red"});
                    $('#readCardStatus').html('读取卡失败');
                }
            } else if (!isEmpty(tempPassSearch.checkDeviceSerializeNumber) && tempPassSearch.checkDeviceSerializeNumber == data.serialNumber) {
                // 检测设备成功时
                tempPassSearch.checkdevice_status = 1;
                tempPassSearch.checkDeviceSerializeNumber = undefined;
                var $device = tempPassSearch.$parent.find('#device').data('kendoDropDownList');
                var result = $device.dataItem($device.select());
                tempPassSearch.devInfo = result;
                tempPassSearch.$parent.find('#device_status').html(result.deviceName + ' (' + result.deviceCode + ')');
                tempPassSearch.$parent.find('#device_status').css({'color':'green'});
                tempPassSearch.timerRead = setInterval(function() {
                    tempPassSearch.readCard();
                }, 1000);
            }
        } else {
            notification({title : '提示', message : '设备连接，请检测设备是否连接或重启设备后再试'}, 'info');
            clearInterval(tempPassSearch.timerRead);
            return;
        }
    },
    readCard : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (_this.checkdevice_status != 1) {
            notification({title : '操作失败', message : '请在读卡前测试设备是否连接成功'}, 'info');
            clearInterval(tempPassSearch.timerRead);
            return;
        }
        _this.readCardStatus = 0;
        var $device = _this.$parent.find('#device').data('kendoDropDownList');
        var result = $device.dataItem($device.select());
        var jna = {};
        jna["reader"] = 0; //毒头？
        jna["sector"] = 15; //扇区号
        jna["deviceCacheInfo"] = result;
        var jnaStr = JSON.stringify(jna);
        tempPassSearch.readCardSerializeNumber = _this.ws.sendMsgToWebSocket(jnaStr,"RC").serialNumber;
    },
    searchTempPass : function (devInfo, phyid, phytyp, cardno) {
        var _this = this;
        clearInterval(_this.timerRead);
        var logicNo = cardno;
        var dataT = {'devInfo':devInfo, 'phyid':phyid, 'phytyp':phytyp, 'logicNo':logicNo};
        JsonpAjax(baseApiPath + 'temp_pass/check/'+logicNo, JSON.stringify(dataT), 'json', function(res) {
            if (isEmpty(res.value)) {
                _this.console.print('[' + new Date().pattern("MM/dd HH:mm:ss") + ']  <span style="color: darkred">'+res.msg+'</span><br><br><br>');
                _this.successPhyid = phyid;
                return;
            }
            _this.successPhyid = res.value.physicNumber;
            var whileMsg = '<span style="display: none" id="cr-'+_this.successPhyid+'">';
            whileMsg += ('#################  卡信息  ################<br>');
            whileMsg += ('#&nbsp;&nbsp;&nbsp;通行证：{' + _this.successPhyid  + '} 信息如下：<br>');
            whileMsg += ('--------------------------------------------------------<br>');
            whileMsg += ('-&nbsp;&nbsp;&nbsp;&nbsp;[通行证编号]<span style="color: darkgreen">&nbsp;'+res.value.uniqueIdentifier+'</span><br>');
            whileMsg += ('-&nbsp;&nbsp;&nbsp;&nbsp;[逻辑编号]<span style="color: darkgreen">&nbsp;&nbsp;&nbsp;&nbsp;'+res.value.rationUniqueIdentifier+'</span><br>');
            whileMsg += ('-&nbsp;&nbsp;&nbsp;&nbsp;[物理编号]<span style="color: darkgreen">&nbsp;&nbsp;&nbsp;&nbsp;'+res.value.physicNumber+'</span><br>');
            var typeTitle = '';
            if (res.value.crTrafficPermitType.trafficPermitType == 0) {
                typeTitle = '临时卡';
            } else if (res.value.crTrafficPermitType.trafficPermitType == 1) {
                typeTitle = '包期卡';
            } else if (res.value.crTrafficPermitType.trafficPermitType == 2) {
                typeTitle = '储值卡';
            } else {
                typeTitle = '未知类型';
            }
            whileMsg += ('-&nbsp;&nbsp;&nbsp;&nbsp;[通行类型]<span style="color: darkgreen">&nbsp;&nbsp;&nbsp;&nbsp;'+res.value.crTrafficPermitType.trafficPermitName+' ('+typeTitle+')</span><br>');
            whileMsg += ('-&nbsp;&nbsp;&nbsp;&nbsp;[有效时间]<span style="color: darkgreen">&nbsp;&nbsp;&nbsp;&nbsp;'+res.value.beginTime + '~' + res.value.endTime+'</span><br>');
            whileMsg += ('--------------------------------------------------------<br>');
            whileMsg += ('#################  卡信息  ################<br><br><br><br>');
            whileMsg += '</span>';
            _this.console.print(whileMsg);
            _this.$parent.find('#cr-'+_this.successPhyid).fadeIn();
            _this.timerRead = setInterval(function() {
                _this.readCard();
            }, 1000);
        }, true);
    }
}
